<?php
namespace Home\Controller;
use Think\Controller;
class IndexController extends Controller {
    
    protected $font = 'SourceHanSansCN-Medium.otf';                 //字体文件
    protected $fontColor = '#950c22';                 //水印字体颜色
    protected $saveName = '';
    protected $savePath = "./Upload/water/";     //图片保存路径
    protected $tplPath  = './html/img/';//模板图片路径
    protected $fontSize = 60;
    protected $textWidth = 500;//文本宽度限制

    
    public function _initialize(){
        $this->saveName = md5(uniqid().time()).'.jpg';
        $this->outPutPath = $this->savePath.$this->saveName;
        
    }
    
    public function index($text='五个字五个',$imgId=0){
        $tplPath = $this->tplPath.'mid_bg'.$imgId.'.jpg';
        
//         if (strlen($text) > 14) $this->error("超过15个字数,会不好看的!");

        
        $image = new \Think\Image(); 
        
        //文本超长换行处理
//         $text = $this->autowrap($this->fontSize, 0, $this->font, $text,$this->textWidth);
        
        $imageFile=$image->open($tplPath);
        $len = mb_strlen($text,'UTF8');
//         dump($len);exit();
//         $offset=[215,200,180,165,140];

        $imageFile->text($text,"./$this->font",$this->fontSize,$this->fontColor,\Think\Image::IMAGE_WATER_NORTHWEST,[385,310],13);

        
        $imageFile->save($this->outPutPath); 
        
        $data['path'] = $this->outPutPath;
        $data['status'] = 1;
        $data['info'] = '图片生成成功';
//         $urlindex = U('');
//         echo "<img src='.$this->outPutPath' alt='' /><a href='$urlindex'>刷新</a>";
//         exit();
        $this->ajaxReturn($data);
        
    }
    
    
    /**
     * 文本自动换行
     * 将空格作为分隔符，将字符串分割为一个个单词，然后再一个接一个地拼接在一起，判断其长度是否超过画布，若超过则换行再拼接，否则继续拼接。
     * @param unknown $fontsize
     * @param unknown $angle
     * @param unknown $fontface
     * @param unknown $string
     * @param unknown $width
     * @return string|unknown
     * date:2016年8月9日
     * author: EK_熊
     */
    function autowrap($fontsize, $angle, $fontface, $string, $width) {
        // 这几个变量分别是 字体大小, 角度, 字体名称, 字符串, 预设宽度
        $content = "";
    
        // 将字符串拆分成一个个单字 保存到数组 letter 中
        for ($i=0;$i<mb_strlen($string);$i++) {
            $letter[] = mb_substr($string, $i, 1);
        }
    
        foreach ($letter as $l) {
            $teststr = $content." ".$l;
            $testbox = imagettfbbox($fontsize, $angle, $fontface, $teststr);
            // 判断拼接后的字符串是否超过预设的宽度
            if (($testbox[2] > $width) && ($content !== "")) {
                $content .= "\n";
            }
            $content .= $l;
        }
        return $content;
    }
    
}